#include <srs_app_heartbeat.hpp>

#ifdef SRS_AUTO_HTTP_CORE

#include <sstream>
using namespace std;

#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_app_config.hpp>
#include <srs_app_http_client.hpp>
#include <srs_protocol_json.hpp>
#include <srs_app_utility.hpp>
#include <srs_core_autofree.hpp>
#include <srs_app_http_conn.hpp>

SrsHttpHeartbeat::SrsHttpHeartbeat() {
}

SrsHttpHeartbeat::~SrsHttpHeartbeat() {
}

void SrsHttpHeartbeat::heartbeat() {
    int ret = ERROR_SUCCESS;
    auto pheartbt = _srs_config->get_heartbeart();

    auto& url = _srs_config->get_heartbeat_url(pheartbt);

    SrsHttpUri uri;
    if ((ret = uri.initialize(url)) != ERROR_SUCCESS) {
        srs_error("http uri parse hartbeart url failed. url=%s, ret=%d", url.c_str(), ret);
        return;
    }

    string ip = "";
    auto& device_id = _srs_config->get_heartbeat_device_id(pheartbt);

    auto& ips = srs_get_local_ipv4_ips();
    if (!ips.empty()) {
        ip = ips[_srs_config->get_stats_network() % (int)ips.size()];
    }

    stringstream ss;
    ss << SRS_JOBJECT_START
       << SRS_JFIELD_STR("device_id", device_id) << SRS_JFIELD_CONT
       << SRS_JFIELD_STR("ip", ip);
    if (_srs_config->get_heartbeat_summaries(pheartbt)) {
        ss << SRS_JFIELD_CONT << SRS_JFIELD_ORG("summaries", "");
        srs_api_dump_summaries(ss);
    }
    ss << SRS_JOBJECT_END;

    auto req = ss.str();

    SrsHttpClient http;
    if ((ret = http.initialize(uri.get_host(), uri.get_port())) != ERROR_SUCCESS) {
        return;
    }

    ISrsHttpMessage* msg = NULL;
    if ((ret = http.post(uri.get_path(), req, &msg)) != ERROR_SUCCESS) {
        srs_info("http post hartbeart uri failed. url=%s, request=%s, ret=%d", url.c_str(), req.c_str(), ret);
        return;
    }
    SrsAutoFree(ISrsHttpMessage, msg);

    string res;
    if ((ret = msg->body_read_all(res)) != ERROR_SUCCESS) {
        return;
    }

    srs_info("http hook hartbeart success. url=%s, request=%s, response=%s, ret=%d", url.c_str(), req.c_str(), res.c_str(), ret);
    return;
}

#endif

